package com.beemans.common.utils

import com.beemans.common.app.CommonConfig
import com.beemans.common.data.bean.HwMarketData
import com.beemans.common.data.bean.HwMarketResponse
import com.beemans.common.data.constant.CommonStore
import com.beemans.common.ext.stringCallback
import com.blankj.utilcode.util.NetworkUtils
import com.tiamosu.fly.http.FlyHttp
import com.tiamosu.fly.http.request.base.BaseRequest
import java.net.URLEncoder

/**
 * @author tiamosu
 * @date 2021/3/12
 */
object NetUtils {

    /**
     * 获取网络类型
     */
    @Suppress("DEPRECATION")
    fun getNetType(): String {
        return when (NetworkUtils.getNetworkType()) {
            NetworkUtils.NetworkType.NETWORK_ETHERNET -> "ETHERNET"
            NetworkUtils.NetworkType.NETWORK_WIFI -> "WIFI"
            NetworkUtils.NetworkType.NETWORK_5G -> "5G"
            NetworkUtils.NetworkType.NETWORK_4G -> "4G"
            NetworkUtils.NetworkType.NETWORK_3G -> "3G"
            NetworkUtils.NetworkType.NETWORK_2G -> "2G"
            NetworkUtils.NetworkType.NETWORK_UNKNOWN -> "UNKNOWN"
            else -> "NETWORK_NO"
        }
    }

    /**
     * 通过应用名称在华为应用市场查询应用版本信息
     */
    fun getAppInfoByHwMarket(
        appName: String = CommonConfig.appName,
        baseRequest: BaseRequest<*>.() -> Unit = {},
        isShowLoading: Boolean = false,
        callback: (data: HwMarketData?) -> Unit
    ) {
        FlyHttp[CommonStore.HW_MARKET_QUERY_URL]
            .params("uri", "searchApp|" + URLEncoder.encode(appName, "UTF-8"))
            .params("method", "internal.getTabDetail")
            .params("serviceType", "20")
            .params("reqPageNum", "1")
            .params("maxResults", "25")
            .params("version", "10.0.0")
            .params("zone", "")
            .params("locale", "zh")
            .retryCount(0)
            .timeOut(3000)
            .apply(baseRequest)
            .build()
            .execute(stringCallback(isShowLoading) {
                onResult { result ->
                    val response = result.getResponse<HwMarketResponse>(true)
                    if (response == null) {
                        callback.invoke(null)
                        return@onResult
                    }
                    val layoutData = response.layoutData
                    for (dataList in layoutData) {
                        for (info in dataList.dataList) {
                            if (CommonConfig.packageName == info.packageName) {
                                callback.invoke(info)
                                return@onResult
                            }
                        }
                    }
                    callback.invoke(null)
                }
            })
    }
}